import React, { useState, useEffect } from "react";

export const Count: React.FC = () => {

    const [count, setCount] = useState(0);

    console.log('触发了组件的渲染')

    const add = () => {
        setCount(count + 1)
    }

    return (
        <>
            <h1>count的值是：{count}</h1>
            <button onClick={add}>加1</button>
        </>
    )
}


export const DateCom: React.FC = () => {
    const [date] = useState(() => {
        const dt = new Date()
        return { year: dt.getFullYear(), month: dt.getMonth() + 1, day: dt.getDate() }
    })
    return (
        <>
            <h1>当前的年月日信息</h1>
            <p>年份：{date.year}</p>
            <p>月份：{date.month}</p>
            <p>日期：{date.day}</p>
        </>
    )
}


export const Counter2: React.FC = () => {

    const [count, setCount] = useState(0);

    const add = () => {
        setCount(count + 1)
    }

    // 依赖count值，回调函数会在count变化时执行
    // 回调函数在组件首次渲染的时候也会执行
    useEffect(() => {
        console.log(`count最新的值是：${count}`)
    }, [count])


    return (
        <>
            <h1>count的值是：{count}</h1>
            <button onClick={add}>加1</button>
        </>
    )
}






export const Counter3: React.FC = () => {

    const [count, setCount] = useState(0);

    const add = () => {
        // setCount内部更新是异步的，但是这里连续两次调用的js是同步的
        // setCount(count + 1)
        // 这里再次调用是，count的状态还有修改过来，还是0，setCount运行了两次，值还是1
        // setCount(count + 1)


        // 解决方法
        setCount(prev => prev + 1)
        setCount(prev => prev + 1)
    }

    return (
        <>
            <h1>count的值是：{count}</h1>
            <button onClick={add}>加1</button>
        </>
    )
}


export const UserInfo: React.FC = () => {
    const [user, setUser] = useState({
        name: '张三',
        age: 18,
        gender: '男'
    })

    const edit = () => {
        user.name = '李四'
        user.age = 20
        //    setUser(user)  //无效
        //    setUser({...user}) 
        setUser(Object.assign({}, user))
    }

    return (
        <>
            <h1>用户信息：</h1>
            <p>姓名：{user.name}</p>
            <p>年龄：{user.age}</p>
            <p>性别：{user.gender}</p>
            <br />
            <button onClick={edit}>修改用户信息</button>
        </>
    )
}


export const FUpdate: React.FC = () => {
    const [, forceUpdate] = useState({})
    const update = () => {
        // 每次传入一个新对象，组件就会刷新
        forceUpdate({})
    }
    return (
        <>
            <h1>{Date.now()}</h1>
            <button onClick={update}>强制刷新</button>
        </>
    )
}